<!-- 校区负责人下的合同管理页面 -->
<template>
  <div class="main">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="开始时间" prop="startDate">
        <div class="block">
          <el-date-picker
            v-model="queryParams.startDate"
            type="datetime"
            placeholder="请选择开始时间"
          />
        </div>
      </el-form-item>
      <el-form-item label="结束时间" prop="startDate">
        <div class="block">
          <el-date-picker
            v-model="queryParams.endDate"
            type="datetime"
            placeholder="请选择结束时间"
          />
        </div>
      </el-form-item>
      <el-form-item label="金额范围" prop="contractAmount">
        <el-input-number
          v-model="queryParams.contractAmount"
          :min="0"
          :precision="2"
          :step="1000"
        />
      </el-form-item>
      <el-form-item label="支付状态" prop="paymentStatus">
        <el-select
          v-model="queryParams.paymentStatus"
          placeholder="请选择支付状态"
          filterable
        >
          <el-option label="未支付" value="未支付"></el-option>
          <el-option label="部分支付" value="部分支付"></el-option>
          <el-option label="已支付" value="已支付"></el-option>
          <el-option label="拒签" value="拒签"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="签约时间" prop="signTime">
        <el-date-picker
          v-model="queryParams.signTime"
          type="datetime"
          placeholder="签约时间"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" size="default" @click="searchBtn()"
          >搜索</el-button
        >
        <el-button size="default" @click="resetBtn">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="middle">
      <div class="add" style="margin-left: 20px">
        <div class="button">
          <el-button type="primary" :icon="Plus" @click="handleAdd()"
            >申请入驻</el-button
          >
        </div>
      </div>
    </div>

    <el-empty description="暂无签订的合同" v-show="emptyShow" />

    <el-table
      :data="filterTableData"
      row-key="contractId"
      style="width: 100%"
      v-show="!emptyShow"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" />
      <el-table-column label="序号" prop="index">
        <template #default="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column label="校区id" prop="campusId" />
      <el-table-column label="合同名称" prop="contractName" />
      <el-table-column label="合同文件ID" prop="fileId" />
      <el-table-column label="开始日期" prop="startDate" />
      <el-table-column label="结束日期" prop="endDate" />
      <el-table-column label="金额" prop="contractAmount" />
      <el-table-column label="支付状态" prop="paymentStatus" />
      <el-table-column
        label="签约时间"
        prop="signTime"
        :formatter="(row) => formatDate(row.signTime, 'YYYY-MM-DD HH:mm:ss')"
      />
      <el-table-column label="备注" prop="note" />

      <el-table-column align="right">
        <template #header>
          <el-input
            v-model="search"
            size="small"
            placeholder="请输入合同名称"
          />
        </template>
        <template #default="scope">
          <el-button
            size="large"
            type="success"
            @click="handleEdit(scope.$index, scope.row)"
          >
            查看合同详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      size="default"
      v-show="!emptyShow"
      :disabled="disabled"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog v-model="dialogVisible" :modal="true" width="800px">
      <el-form :model="formData" :rules="rules" ref="categoryForm">
        <h1 class="formTitle">申请入驻</h1>
        <el-row>
          <el-col :span="11">
            <el-form-item label="营业执照" label-width="120px" prop="License">
              <!-- 营业执照图片上传 -->
              <el-upload
                v-model:file-list="formData.License"
                :auto-upload="false"
                list-type="picture-card"
                :limit="1"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                accept=".jpg,.jpeg,.png"
              >
                <el-icon><Plus /></el-icon>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传jpg/png格式的营业执照，大小不超过5MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="法人身份证" label-width="120px" prop="idCard">
              <!-- 身份证图片上传 -->
              <el-upload
                v-model:file-list="formData.idCard"
                :auto-upload="false"
                list-type="picture-card"
                :limit="1"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                accept=".jpg,.jpeg,.png"
              >
                <el-icon><Plus /></el-icon>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传身份证(人像面)照片，大小不超过5MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item
              label="报价（单位:元）"
              label-width="120px"
              prop="contractAmount"
            >
              <el-input-number
                v-model="formData.contractAmount"
                :min="0"
                :precision="2"
                :step="1000"
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item
              label="校区名称"
              label-width="120px"
              prop="campusName"
            >
              <el-input
                v-model="formData.campusName"
                placeholder="请输入校区名"
                label-width="120"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="开始时间" label-width="120px" prop="startDate">
              <div class="block">
                <el-date-picker
                  v-model="formData.startDate"
                  type="date"
                  value-format="YYYY-MM-DD HH:mm"
                  format="YYYY-MM-DD HH:mm"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="结束时间" label-width="120px" prop="endDate">
              <div class="block">
                <el-date-picker
                  v-model="formData.endDate"
                  type="date"
                  value-format="YYYY-MM-DD HH:mm"
                  format="YYYY-MM-DD HH:mm"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="电话" label-width="120px" prop="phone">
              <el-input v-model="formData.phone" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="邮箱" label-width="120px" prop="Email">
              <el-input v-model="formData.Email" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCanle">取消</el-button>
          <el-button type="primary" @click="handleConfirm"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { formatDate, formatDateUTC } from "@/utils/dateFormat";
import { insertApplyForEntry, paginationContract } from "@/api/leader";
import { ElMessage } from "element-plus";
import {
  Calendar,
  Search,
  Edit,
  Plus,
  Delete,
  Phone,
} from "@element-plus/icons-vue";

const user = {
  userId: "4",
  userAcc: "campus1",
  userPwd: "e10adc3949ba59abbe56e057f20f883e",
  userName: "王校区",
  userSex: "女",
  userPhone: "13800138003",
  userEmail: "campus1@example.com",
  userStatus: "正常",
  lastLoginTime: "2025-05-17 19:38:01",
  createTime: "2025-05-17 19:38:01",
  userNote: "北京校区负责人",
};
const single = ref(true);
const multiple = ref(true);
const selectRow = ref([]);
const dialogVisible = ref(false);
const emptyShow = ref(false);
const search = ref("");
//是否禁用表单
const disabled = ref(false);
// 表单参数
var formData = ref({
  License: [], // 营业执照文件列表
  idCard: [], // 身份证文件列表
  campusName: "", //校区名称
  startDate: "",
  endDate: "",
  contractAmount: 0,
  Phone: "",
  Email: "",
});
//重置表单
function resetForm() {
  formData.value = {
    License: [],
    idCard: [],
    campusName: "",
    startDate: "",
    endDate: "",
    contractAmount: 0,
    phone: "",
    email: "",
  };
}
//分页组件
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const filterTableData = computed(() =>
  tableData.value.filter(
    (data) =>
      !search.value ||
      data.contractName.toLowerCase().includes(search.value.toLowerCase())
  )
);

const handleSizeChange = (val) => {
  pageSize.value = val;
  hanldePage();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  hanldePage();
};
//分页函数
async function hanldePage() {

  const params = {
    pageSize: pageSize.value,
    currentPage: currentPage.value,
    userId: parseInt(user.userId),
    contractAmount: queryParams.value.contractAmount || 0,
    paymentStatus: queryParams.value.paymentStatus || "",
    startDate: queryParams.value.startDate,
    endDate: queryParams.value.endDate,
    signTime: queryParams.value.signTime,
  };

  // 查找校区负责人ID对应的合同
  try {
    const response = await paginationContract(params);

    total.value = response.data.contracts.total;

    if (response.code === 200) {
      // 根据实际API返回格式调整
      tableData.value = response.data.contracts.records || []; // 更新表格数据
      emptyShow.value = tableData.value.length === 0; // 控制空状态显示
      console.log(tableData.value);
      console.log("获取合同列表成功:", tableData.value);
    } else {
      ElMessage.error(response.message || "获取合同列表失败");
    }
  } catch (error) {
    console.error("获取合同列表出错:", error);
    ElMessage.error("获取合同列表失败，请稍后重试");
  }
}

//生命周期函数
onMounted(async () => {
  hanldePage();
});

//查询参数
const queryParams = ref({
  contractId: "",
  campusId: "",
  contractName: "",
  fileId: "",
  startDate: "",
  endDate: "",
  contractAmount: 0,
  paymentStatus: "",
  signTime: "",
  note: "",
});
//校验规则
const rules = {
  License: [
    { required: true, message: "请上传营业执照", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (value.length === 0) callback(new Error("请上传营业执照"));
        else callback();
      },
    },
  ],
  idCard: [
    { required: true, message: "请上传身份证人像面", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (value.length === 0) callback(new Error("请上传身份证人像面"));
        else callback();
      },
    },
  ],
   phone: [
    {
      required: true,
      message: "请输入电话号码",
      trigger: "blur",
    },
    {
      pattern: /^1[3-9]\d{9}$/, // 匹配1开头的11位手机号
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  Email: [
    {
      required: true,
      message: "请输入邮箱",
      trigger: "blur",
    },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, // 标准邮箱格式
      message: "请输入正确的邮箱格式",
      trigger: "blur",
    },
  ],
};
// 重置按钮
function resetBtn() {
    currentPage.value=1,
    pageSize.value=10,
    total.value=0,
  queryParams.value = {
    contractName: "",
    fileId: "",
    startDate: "",
    endDate: "",
    contractAmount: 0,
    paymentStatus: "",
    signTime: "",
    note: "",
  };
}
const tableData = ref([]);

async function searchBtn() {
  queryParams.value.signTime = formatDateUTC(
    queryParams.value.signTime,
    "YYYY-MM-DD"
  ); // 签约时间

  queryParams.value.startDate = formatDateUTC(
    queryParams.value.startDate,
    "YYYY-MM-DD"
  ); // 起始日期
  queryParams.value.endDate = formatDateUTC(
    queryParams.value.endDate,
    "YYYY-MM-DD"
  ); // 结束日期
  currentPage.value=1;
  hanldePage();
}

// 选中某一列
function handleSelectionChange(selected) {
  single.value = selected.length != 1;
  multiple.value = selected.length == 0;
  selectRow.value = selected;
}

//查看合同详情
const handleEdit = (index, row) => {
  console.log(index, row);
};

//新增
function handleAdd() {
  resetForm();
  dialogVisible.value = true;
}

//关闭dialog
function handleCanle() {
  dialogVisible.value = false;
}
const categoryForm = ref(null); // 声明表单引用

//确认表单
const handleConfirm = async () => {
  try {
    // 1. 表单验证
    await categoryForm.value.validate();

    // // 2. 文件校验
    if (formData.value.License.length === 0) {
      ElMessage.error("请上传营业执照");
      return;
    }
    if (formData.value.idCard.length === 0) {
      ElMessage.error("请上传身份证正反两面");
      return;
    }

    // 3. 创建FormData对象
    const fd = new FormData();

    // 4. 添加文件
    formData.value.License.forEach((file) => fd.append("license", file.raw));
    formData.value.idCard.forEach((file) => fd.append("idCard", file.raw));

    // 5. 添加其他表单字段
    fd.append("contractAmount", formData.value.contractAmount);
    fd.append("campusName", formData.value.campusName);
    fd.append("startDate", formData.value.startDate);
    fd.append("endDate", formData.value.endDate);
    fd.append("phone", formData.value.phone);
    fd.append("email", formData.value.Email);

    // 6. 发送请求
    const response = await insertApplyForEntry(fd);
    console.log(response);
    resetForm();
  } catch (error) {
    console.error("提交出错:", error);
    ElMessage.error("提交失败，请检查表单");
  }
};

// 文件类型校验
const beforeUpload = (rawFile) => {
  if (!["image/jpeg", "image/png"].includes(rawFile.type)) {
    ElMessage.error("只能上传JPG/PNG格式!");
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error("文件大小不能超过5MB!");
    return false;
  }
  return true;
};

// 超出文件数量限制
const handleExceed = (files) => {
  ElMessage.warning(`最多只能上传 ${files.length} 个文件`);
};
</script>

<style scoped>
.main {
  width: 100%;
  height: 100%;
}
.formTitle {
  text-align: center;
  margin-bottom: 20px;
  font-size: 23px;
}
.demo-datetime-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: stretch;
}
.demo-datetime-picker .block {
  padding: 30px 0;
  text-align: center;
}
.line {
  width: 1px;
  background-color: var(--el-border-color);
}
.middle {
  width: 100%;
  height: 8vh;
  /* background-color: antiquewhite; */
  margin-bottom: 20px;
}

.add {
  margin-top: 15px;
  margin-left: 45px;
  width: 5%;
  height: 50%;
  float: left;
}
</style>